<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="月份" prop="workTime">
        <el-date-picker
          v-model="queryParams.workTime"
          type="month"
          placeholder="选择月">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="班组" prop="deptId">
        <el-select
          v-model="queryParams.deptId"
          placeholder="请选择班组"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in deptInfo"
            :key="dict.deptId"
            :label="dict.deptName"
            :value="dict.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleGenerate"
          v-hasPermi="['pay:generate']"
        >生成工资表
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          @click="handleExport"
          :disabled="single"
          :loading="exportLoading"
          v-hasPermi="['pay:export']"
        >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-check"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['pay:delete']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="payList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" align="center"/>
      <!--      <el-table-column label="序号" align="center" type="index"/>-->
      <el-table-column label="班组" align="center" prop="deptName" width="190px"/>
      <el-table-column label="工资单月份" align="center" prop="workTime"/>
      <el-table-column label="应发工资总额" align="center" prop="salarySum"/>
      <el-table-column label="实发工资总额" align="center" prop="actualSalarySum"/>
      <el-table-column label="生成人员" align="center" prop="createBy"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="140px" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleCheck(scope.row)"
            v-hasPermi="['pay:detail']"
          >详情
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPermi="['pay:edit']"
          >编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生成月份" prop="workTime">
          <el-date-picker
            v-model="form.workTime"
            type="month"
            placeholder="选择月">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="班组" prop="deptId">
          <el-select
            v-model="form.deptId"
            placeholder="请选择班组"
            clearable
          >
            <el-option
              v-for="dict in deptInfo"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listSalary, saveSalary, delSalary, exportSalary } from "@/api/personnel/pay/main";
  import {tableRecords} from "@/api/system/dept";
  import {parseTime} from "@/utils/ruoyi";

  export default {
    name: "Scheme",
    data() {
      return {
        //班组
        deptInfo: null,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 职级列表
        payList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 状态数据字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          workTime: undefined,
          deptId: undefined,
        },
        //提交审核表单
        auditParam: {
          processInstanceName: undefined,
          businessKey: undefined,
          processDefinitionKey: 'yyxq_audit',
          variables: undefined,
          processType: 1
        },
        //审核撤销
        delAuditParam: {
          taskId: undefined,
          reason: undefined,
          processType: 1,
        },
        //审核参数
        variablesMap: {
          auditFlag: undefined,
          orderCode: undefined
        },
        // 表单参数
        form: {
          workTime: undefined,
          deptId: undefined,
        },
        // 表单校验
        rules: {
          workTime: [
            {required: true, message: "请选择", trigger: "change"}
          ],
          deptId: [
            {required: true, message: "请选择", trigger: "change"}
          ],
        }
      };
    },
    created() {
      this.getList();
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      //获取班组数据
      this.getDept();
    },
    methods: {
      /** 查询列表 */
      getList() {
        this.loading = true;
        // console.log(this.queryParams)
        const query = this.queryParams;
        const params = { ...query, workTime: parseTime(query.workTime,'{y}-{m}-{d}')}
        // console.log(params)
        listSalary(params).then(response => {
          // console.log(response)
          this.payList = response.rows;
          this.total = response.total;
          this.loading = false;
        }).catch(e=>{
          console.log(e)
        });
      },
      //查询班组数据
      getDept(){
        tableRecords({category:2}).then(response => {
          // console.log(response)
          this.deptInfo = response.rows;
        })
      },
      // 岗位状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          postId: undefined,
          postCode: undefined,
          postName: undefined,
          postSort: 0,
          status: "0",
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      //导出
      handleExport(){
        const id = this.ids[0];
        // console.log(id);
        const params = { salarySumId: id };
        this.exportLoading = true;
        exportSalary(params).then(res=>{
          // console.log(res)
          this.download(res.msg);
          this.exportLoading = false;
        }).catch(() => {});
      },
      /** 生成工资表按钮操作 */
      handleGenerate() {
        this.title = "生成工资表";
        this.open = true;
        this.form = {
          ...this.form,
          type: 'generate',
        }
      },
      /** 编辑按钮操作 */
      handleEdit(row) {
        console.log(row);
        const params = { ...row, action: 'edit'};
        this.$router.push({
          path: "/finance/longWorkerEdit",
          query: params
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            const { workTime, deptId } = this.form;
            let deptName = null;
            this.deptInfo.forEach(item=>{
              if(item.deptId === deptId){
                deptName = item.deptName
              }
            })
            const params = {
              workTime: parseTime(workTime,'{y}-{m}'),
              deptId: deptId,
              deptName: deptName,
            }
            // console.log(params);
            saveSalary(params).then(res =>{
              if (res && res.code === 200) {
                this.msgSuccess(res.msg || "考勤生成成功");
                this.open = false;
                //重新获取列表
                this.queryParams.pageNum = 1;
                this.getList()
              } else {
                this.msgError(res&&res.msg || '考勤生成错误')
              }
            })
          }
        });
      },
      /** 详情按钮操作 */
      handleCheck(row) {
        const params = row;
        this.$router.push({path: "/finance/longWorkerDetail", query: params });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        const _this = this;
        this.$confirm('是否确认删除工资单编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          const params = ids;
          _this.delSalary(params);
        }).catch((e) => {
          console.log(e)
        });
      },
      //删除接口
      delSalary(ids) {
        delSalary(ids).then(res => {
          console.log(res)
          if (res && res.code === 200) {
            this.msgSuccess(res.msg || "删除成功");
            //重新获取列表
            this.queryParams.pageNum = 1;
            this.getList()
          } else {
            this.msgError(res&&res.msg || '删除错误')
          }
        })
      },
    }
  };
</script>
